package com.zhiche.wms.service.otm.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.wms.configuration.MyConfigurationProperties;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.RestfulResponse;
import com.zhiche.wms.core.supports.enums.InterfaceAddrEnum;
import com.zhiche.wms.core.supports.enums.InterfaceEventEnum;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.core.utils.HttpClientUtil;
import com.zhiche.wms.core.utils.SnowFlakeId;
import com.zhiche.wms.domain.mapper.log.ItfExplogLineMapper;
import com.zhiche.wms.domain.mapper.opbaas.StatusLogMapper;
import com.zhiche.wms.domain.mapper.otm.OtmOrderReleaseMapper;
import com.zhiche.wms.domain.mapper.otm.ShipmentRecordMapper;
import com.zhiche.wms.domain.model.log.ItfExplogLine;
import com.zhiche.wms.domain.model.opbaas.StatusLog;
import com.zhiche.wms.domain.model.otm.OtmOrderRelease;
import com.zhiche.wms.domain.model.otm.OtmReleaseOtmDTO;
import com.zhiche.wms.domain.model.otm.OtmShipment;
import com.zhiche.wms.domain.mapper.otm.OtmShipmentMapper;
import com.zhiche.wms.domain.model.otm.ShipmentInfo;
import com.zhiche.wms.dto.opbaas.resultdto.ShipmentForShipDTO;
import com.zhiche.wms.dto.opbaas.resultdto.ShipmentRecordDTO;
import com.zhiche.wms.service.log.IItfExplogLineService;
import com.zhiche.wms.service.otm.IOtmOrderReleaseService;
import com.zhiche.wms.service.otm.IOtmShipmentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 调度指令 服务实现类
 * </p>
 *
 * @author zhaoguixin
 * @since 2018-06-13
 */
@Service
public class OtmShipmentServiceImpl extends ServiceImpl<OtmShipmentMapper, OtmShipment> implements IOtmShipmentService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OtmShipmentServiceImpl.class);
    @Autowired
    private SnowFlakeId snowFlakeId;

    @Autowired
    private IOtmOrderReleaseService otmOrderReleaseService;

    @Autowired
    private ShipmentRecordMapper shipmentRecordMapper;
    @Autowired
    private OtmOrderReleaseMapper otmOrderReleaseMapper;

    @Autowired
    private StatusLogMapper statusLogMapper;
    @Autowired
    private IItfExplogLineService logLineService;
    @Autowired
    private MyConfigurationProperties properties;
    @Autowired
    private ItfExplogLineMapper itfExplogLineMapper;

    @Override
    @Transactional
    public boolean insertShipment(OtmShipment otmShipment) {
        otmShipment.setId(snowFlakeId.nextId());
        for(OtmOrderRelease otmOrderRelease : otmShipment.getOtmOrderReleaseList()){
            otmOrderRelease.setId(snowFlakeId.nextId());
        }
        return otmOrderReleaseService.insertBatch(otmShipment.getOtmOrderReleaseList()) && insert(otmShipment);
    }

    /**
     * 模糊查询指令列表  -- 关联发车配置点
     *
     */
    @Override
    public List<ShipmentForShipDTO> queryShipmentReleaseList(Page<ShipmentForShipDTO> page, HashMap<String, Object> param, EntityWrapper<ShipmentForShipDTO> ew) {
        return baseMapper.queryShipmentReleaseList(page,param, ew);
    }

    /**
     * 装车发运-点击获取指令详情
     */
    @Override
    public List<ShipmentForShipDTO > getShipDetail(EntityWrapper<ShipmentForShipDTO > ew) {
        return baseMapper.getShipDetail(ew);
    }

    @Override
    public int countShipmentReleaseList(HashMap<String, Object> params, EntityWrapper<ShipmentForShipDTO> ew) {
        return baseMapper.countShipmentReleaseList(params, ew);
    }

    @Override
    public List<ShipmentForShipDTO> queryShipmentReleases(EntityWrapper<ShipmentForShipDTO> dataEW) {
        return baseMapper.queryShipmentReleases(dataEW);
    }

    @Override
    public List<ShipmentRecordDTO> queryShipRecordList (Page<ShipmentRecordDTO> page, EntityWrapper<ShipmentRecordDTO> ew) {
        return shipmentRecordMapper.queryShipRecordList(page,ew);
    }

    @Override
    public List<OtmOrderRelease> queryShipmentStatus (List<Map<String, String>> shipmentGid) {
        if (CollectionUtils.isEmpty(shipmentGid)) {
            throw new BaseException("查询参数为空，请传递指令号和运单号");
        }

        StringBuffer shipmentGids = new StringBuffer();
        StringBuffer releaseGids = new StringBuffer();
        for (Map<String, String> param : shipmentGid) {
            shipmentGids.append(param.get("shipmentGid")).append(",");
            releaseGids.append(param.get("releaseGid")).append(",");
        }

        Wrapper<OtmOrderRelease> ew = new EntityWrapper<>();
        ew.ne("status", TableStatusEnum.STATUS_50.getCode());
        ew.in("shipment_gid", Arrays.asList(shipmentGids.toString().split(",")));
        ew.in("release_gid", Arrays.asList(releaseGids.toString().split(","))).orderBy("gmt_modified", false);
        List<OtmOrderRelease> otmOrderRelease = otmOrderReleaseMapper.selectList(ew);

        if(CollectionUtils.isNotEmpty(otmOrderRelease)){
            for(OtmOrderRelease orderRelease : otmOrderRelease){
                if(!orderRelease.getStatus().equals(TableStatusEnum.STATUS_BS_DISPATCH.getCode())){
                    Wrapper<StatusLog> statusLogWrapper = new EntityWrapper<>();
                    statusLogWrapper.eq("table_id",orderRelease.getId());
                    statusLogWrapper.eq("table_type",TableStatusEnum.STATUS_10.getCode());
                    statusLogWrapper.eq("status",TableStatusEnum.STATUS_BS_DISPATCH.getCode());
                    List<StatusLog> statusLogs = statusLogMapper.selectList(statusLogWrapper);
                    if(CollectionUtils.isNotEmpty(statusLogs)){
                        orderRelease.setStatus(TableStatusEnum.STATUS_BS_DISPATCH.getCode());
                    }
                }
            }
        }
        LOGGER.info("人送/运力根据指令号和运单号查询结果为{}", otmOrderRelease);
        return otmOrderRelease;
    }

    @Override
    public List<ShipmentRecordDTO> queryNewChannelReleaseList (Page<ShipmentRecordDTO> page, EntityWrapper<ShipmentRecordDTO> ew) {
        return shipmentRecordMapper.queryNewChannelReleaseList(page,ew);
    }

    @Override
    public Page<OtmReleaseOtmDTO> queryPushShipmentOtm (Page<OtmReleaseOtmDTO> page) {
        EntityWrapper<OtmReleaseOtmDTO> oorEW = new EntityWrapper<>();
        oorEW.eq("oorStatus", TableStatusEnum.STATUS_BS_DISPATCH.getCode());
        Map<String, Object> condition = page.getCondition();
        if (Objects.nonNull(condition)) {
            if (Objects.nonNull(condition.get("shipmentGid")) && StringUtils.isNotEmpty((String) condition.get("shipmentGid"))) {
                oorEW.like("shipmentGid", (String) condition.get("shipmentGid"));
            }
            if (Objects.nonNull(condition.get("releaseGid")) && StringUtils.isNotEmpty((String) condition.get("releaseGid"))) {
                oorEW.like("releaseGid", (String) condition.get("releaseGid"));
            }
            if (Objects.nonNull(condition.get("originLocationName")) && StringUtils.isNotEmpty((String) condition.get("originLocationName"))) {
                oorEW.like("originLocationName", (String) condition.get("originLocationName"));
            }
            if (Objects.nonNull(condition.get("vin")) && StringUtils.isNotEmpty((String) condition.get("vin"))) {
                List<String> vins = Arrays.asList(((String) condition.get("vin")).split(","));
                oorEW.in("vin", vins);
            }
            if (Objects.nonNull(condition.get("startTime")) && StringUtils.isNotEmpty((String) condition.get("startTime"))) {
                oorEW.gt("gmtModified", (String) condition.get("startTime"));
            }
            if (Objects.nonNull(condition.get("endTime")) && StringUtils.isNotEmpty((String) condition.get("endTime"))) {
                oorEW.lt("gmtModified", (String) condition.get("endTime"));
            }
        }
        oorEW.orderBy("id", false);
        oorEW.orderBy("gmtModified", false);
        List<OtmReleaseOtmDTO> orderReleases = otmOrderReleaseMapper.queryPushShipmentOtm(page, oorEW);
        LOGGER.info("补发发运数据查询结果为：{}",orderReleases);
        return page.setRecords(orderReleases);
    }

    @Override
    public void pushInboundOtm (Map<String, String> param) {
        if (Objects.isNull(param)) {
            throw new BaseException("入参不能为空");
        }
        if (StringUtils.isEmpty(param.get("keys"))) {
            throw new BaseException("入参【keys】不能为空");
        }
        if (StringUtils.isEmpty(param.get("pushType"))) {
            throw new BaseException("入参【pushType】不能为空");
        }
        EntityWrapper<OtmOrderRelease> ew = new EntityWrapper<>();
        List<String> oorIds = Arrays.asList(param.get("keys").split(","));
        ew.in("id", oorIds);
        List<OtmOrderRelease> otmOrderReleases = otmOrderReleaseMapper.selectList(ew);
        LOGGER.info("wms推送发运数据给tms的查询结果为{}", otmOrderReleases);
        String pushUrl = this.setPushUrl(param.get("pushType"));
        LOGGER.info("需要推送的系统url为{}",pushUrl);
        for (OtmOrderRelease oor : otmOrderReleases) {
            EntityWrapper<ItfExplogLine> logEW = new EntityWrapper<>();
            logEW.eq("relation_id", oor.getId());
            logEW.eq("export_type", InterfaceEventEnum.BS_OP_DELIVERY.getCode());
            List<ItfExplogLine> lines = logLineService.selectList(logEW);
            if (CollectionUtils.isNotEmpty(lines)) {
                ItfExplogLine explogLine = lines.get(0);
                try {
                    LOGGER.info("wms推送发运releaseGid:{},shipmentGid:{}", oor.getReleaseGid(), oor.getShipmentGid());
                    String resJson = HttpClientUtil.postJson(pushUrl, null, explogLine.getDataContent(), 60000);
                    LOGGER.info("wms推送发运结果-->{}", resJson);
                    //更新requestId
                    if (StringUtils.isNotEmpty(resJson)) {
                        RestfulResponse<String> restfulResponse = JSON.parseObject(resJson,new TypeReference<RestfulResponse<String>>() {});
                        if (Objects.nonNull(restfulResponse) && restfulResponse.getCode() == 0) {
                            LOGGER.info("补发发运数据推送返回数据 resJson《requestId》：{}", restfulResponse.getData());
                            ItfExplogLine itfExplogLineParam = new ItfExplogLine();
                            itfExplogLineParam.setRequestId(restfulResponse.getData());
                            EntityWrapper<ItfExplogLine> itfExplogLineEntityWrapper = new EntityWrapper<>();
                            itfExplogLineEntityWrapper.eq("id", explogLine.getId());
                            itfExplogLineMapper.update(itfExplogLineParam, itfExplogLineEntityWrapper);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("wms推送发运失败-->{}", e);
                }
            } else {
                LOGGER.error("WMS推送发运失败--->or的表主键:{},运单:{},指令:{}", oor.getId(), oor.getReleaseGid(), oor.getShipmentGid());
            }
        }
    }

    @Override
    public List<String> queryShipmentInfo (List<String> param) {
        List<String> shipmentList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(param)){
            EntityWrapper<OtmShipment> shipmentEntityWrapper = new EntityWrapper<>();
            shipmentEntityWrapper.in("shipment_gid",param);
            List<OtmShipment> otmShipments = baseMapper.selectList(shipmentEntityWrapper);
            for (OtmShipment otmShipment:otmShipments){
                shipmentList.add(otmShipment.getShipmentGid());
            }
        }
        return shipmentList;
    }

    @Override
    public List<ShipmentInfo> getShipOrderItemCount (List<ShipmentInfo> page) {
        if(CollectionUtils.isNotEmpty(page)){
            for (ShipmentInfo shipmentInfo : page){
                EntityWrapper<OtmOrderRelease> ew = new EntityWrapper<>();
                ew.eq("shipment_gid",shipmentInfo.getShipmwnt_xid());
                ew.ne("status",TableStatusEnum.STATUS_50.getCode());
                int count = otmOrderReleaseMapper.selectCount(ew);
                shipmentInfo.setVehicleQty(count);
            }
        }
        return page;
    }

    /**
     * @param pushType OTM和BMS两个系统
     * @return
     */
    private String setPushUrl (String pushType) {
        String url = "";
        if ("OTM".equals(pushType)) {
            url = properties.getIntegrationhost() + InterfaceAddrEnum.EVENT_URI.getAddress();
        } else if ("TMS".equals(pushType)) {
            url = properties.getShipDataForBMS();
        } else {
            throw new BaseException("推送类型【pushType】不合法");
        }
        return url;
    }
}
